{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# Compare ensemble classifiers using resampling\n",
    "\n",
    "Ensemble classifiers have shown to improve classification performance compare\n",
    "to single learner. However, they will be affected by class imbalance. This\n",
    "example shows the benefit of balancing the training set before to learn\n",
    "learners. We are making the comparison with non-balanced ensemble methods.\n",
    "\n",
    "We make a comparison using the balanced accuracy and geometric mean which are\n",
    "metrics widely used in the literature to evaluate models learned on imbalanced\n",
    "set.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>\n",
    "# License: MIT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Automatically created module for IPython interactive environment\n"
     ]
    }
   ],
   "source": [
    "print(__doc__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load an imbalanced dataset\n",
    "\n",
    "We will load the UCI SatImage dataset which has an imbalanced ratio of 9.3:1\n",
    "(number of majority sample for a minority sample). The data are then split\n",
    "into training and testing.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from imblearn.datasets import fetch_datasets\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "satimage = fetch_datasets()[\"satimage\"]\n",
    "X, y = satimage.data, satimage.target\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Classification using a single decision tree\n",
    "\n",
    "We train a decision tree classifier which will be used as a baseline for the\n",
    "rest of this example.\n",
    "\n",
    "The results are reported in terms of balanced accuracy and geometric mean\n",
    "which are metrics widely used in the literature to validate model trained on\n",
    "imbalanced set.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "tree = DecisionTreeClassifier()\n",
    "tree.fit(X_train, y_train)\n",
    "y_pred_tree = tree.predict(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import balanced_accuracy_score\n",
    "from imblearn.metrics import geometric_mean_score\n",
    "\n",
    "print(\"Decision tree classifier performance:\")\n",
    "print(\n",
    "    f\"Balanced accuracy: {balanced_accuracy_score(y_test, y_pred_tree):.2f} - \"\n",
    "    f\"Geometric mean {geometric_mean_score(y_test, y_pred_tree):.2f}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "from sklearn.metrics import plot_confusion_matrix\n",
    "\n",
    "sns.set_context(\"poster\")\n",
    "\n",
    "disp = plot_confusion_matrix(tree, X_test, y_test, colorbar=False)\n",
    "_ = disp.ax_.set_title(\"Decision tree\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Classification using bagging classifier with and without sampling\n",
    "\n",
    "Instead of using a single tree, we will check if an ensemble of decsion tree\n",
    "can actually alleviate the issue induced by the class imbalancing. First, we\n",
    "will use a bagging classifier and its counter part which internally uses a\n",
    "random under-sampling to balanced each boostrap sample.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import BaggingClassifier\n",
    "from imblearn.ensemble import BalancedBaggingClassifier\n",
    "\n",
    "bagging = BaggingClassifier(n_estimators=50, random_state=0)\n",
    "balanced_bagging = BalancedBaggingClassifier(n_estimators=50, random_state=0)\n",
    "\n",
    "bagging.fit(X_train, y_train)\n",
    "balanced_bagging.fit(X_train, y_train)\n",
    "\n",
    "y_pred_bc = bagging.predict(X_test)\n",
    "y_pred_bbc = balanced_bagging.predict(X_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Balancing each bootstrap sample allows to increase significantly the balanced\n",
    "accuracy and the geometric mean.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Bagging classifier performance:\")\n",
    "print(\n",
    "    f\"Balanced accuracy: {balanced_accuracy_score(y_test, y_pred_bc):.2f} - \"\n",
    "    f\"Geometric mean {geometric_mean_score(y_test, y_pred_bc):.2f}\"\n",
    ")\n",
    "print(\"Balanced Bagging classifier performance:\")\n",
    "print(\n",
    "    f\"Balanced accuracy: {balanced_accuracy_score(y_test, y_pred_bbc):.2f} - \"\n",
    "    f\"Geometric mean {geometric_mean_score(y_test, y_pred_bbc):.2f}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "fig, axs = plt.subplots(ncols=2, figsize=(10, 5))\n",
    "plot_confusion_matrix(bagging, X_test, y_test, ax=axs[0], colorbar=False)\n",
    "axs[0].set_title(\"Bagging\")\n",
    "\n",
    "plot_confusion_matrix(balanced_bagging, X_test, y_test, ax=axs[1], colorbar=False)\n",
    "axs[1].set_title(\"Balanced Bagging\")\n",
    "\n",
    "fig.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Classification using random forest classifier with and without sampling\n",
    "\n",
    "Random forest is another popular ensemble method and it is usually\n",
    "outperforming bagging. Here, we used a vanilla random forest and its balanced\n",
    "counterpart in which each bootstrap sample is balanced.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from imblearn.ensemble import BalancedRandomForestClassifier\n",
    "\n",
    "rf = RandomForestClassifier(n_estimators=50, random_state=0)\n",
    "brf = BalancedRandomForestClassifier(n_estimators=50, random_state=0)\n",
    "\n",
    "rf.fit(X_train, y_train)\n",
    "brf.fit(X_train, y_train)\n",
    "\n",
    "y_pred_rf = rf.predict(X_test)\n",
    "y_pred_brf = brf.predict(X_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similarly to the previous experiment, the balanced classifier outperform the\n",
    "classifier which learn from imbalanced bootstrap samples. In addition, random\n",
    "forest outsperforms the bagging classifier.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Random Forest classifier performance:\")\n",
    "print(\n",
    "    f\"Balanced accuracy: {balanced_accuracy_score(y_test, y_pred_rf):.2f} - \"\n",
    "    f\"Geometric mean {geometric_mean_score(y_test, y_pred_rf):.2f}\"\n",
    ")\n",
    "print(\"Balanced Random Forest classifier performance:\")\n",
    "print(\n",
    "    f\"Balanced accuracy: {balanced_accuracy_score(y_test, y_pred_brf):.2f} - \"\n",
    "    f\"Geometric mean {geometric_mean_score(y_test, y_pred_brf):.2f}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axs = plt.subplots(ncols=2, figsize=(10, 5))\n",
    "plot_confusion_matrix(rf, X_test, y_test, ax=axs[0], colorbar=False)\n",
    "axs[0].set_title(\"Random forest\")\n",
    "\n",
    "plot_confusion_matrix(brf, X_test, y_test, ax=axs[1], colorbar=False)\n",
    "axs[1].set_title(\"Balanced random forest\")\n",
    "\n",
    "fig.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Boosting classifier\n",
    "\n",
    "In the same manner, easy ensemble classifier is a bag of balanced AdaBoost\n",
    "classifier. However, it will be slower to train than random forest and will\n",
    "achieve worse performance.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import AdaBoostClassifier\n",
    "from imblearn.ensemble import EasyEnsembleClassifier, RUSBoostClassifier\n",
    "\n",
    "base_estimator = AdaBoostClassifier(n_estimators=10)\n",
    "eec = EasyEnsembleClassifier(n_estimators=10, base_estimator=base_estimator)\n",
    "eec.fit(X_train, y_train)\n",
    "y_pred_eec = eec.predict(X_test)\n",
    "\n",
    "rusboost = RUSBoostClassifier(n_estimators=10, base_estimator=base_estimator)\n",
    "rusboost.fit(X_train, y_train)\n",
    "y_pred_rusboost = rusboost.predict(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Easy ensemble classifier performance:\")\n",
    "print(\n",
    "    f\"Balanced accuracy: {balanced_accuracy_score(y_test, y_pred_eec):.2f} - \"\n",
    "    f\"Geometric mean {geometric_mean_score(y_test, y_pred_eec):.2f}\"\n",
    ")\n",
    "print(\"RUSBoost classifier performance:\")\n",
    "print(\n",
    "    f\"Balanced accuracy: {balanced_accuracy_score(y_test, y_pred_rusboost):.2f} - \"\n",
    "    f\"Geometric mean {geometric_mean_score(y_test, y_pred_rusboost):.2f}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axs = plt.subplots(ncols=2, figsize=(10, 5))\n",
    "\n",
    "plot_confusion_matrix(eec, X_test, y_test, ax=axs[0], colorbar=False)\n",
    "axs[0].set_title(\"Easy Ensemble\")\n",
    "plot_confusion_matrix(rusboost, X_test, y_test, ax=axs[1], colorbar=False)\n",
    "axs[1].set_title(\"RUSBoost classifier\")\n",
    "\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
